import { defineStore } from "pinia"
import { login, userInfo, logout } from "@/api/user/index"
import { ElNotification } from "element-plus"

export default defineStore("user", {
    state: () => {
        return {
            token: localStorage.getItem("token"),
            userName: "",
            avatar: "",
        }
    },
    getters: {},
    actions: {
        // 登录
        async handleLogin(data) {
            const res: any = await login(data)
            /**
             * code -- 200  表示登录成功
             * code -- 201  表示账号或密码错误
             *
             */

            if (res.code === 200) {
                this.token = res.data
                // 本地持久化
                localStorage.setItem("token", res.data)
                // 返回promise的状态是fulfilled的
                return Promise.resolve("ok")
            } else {
                ElNotification({
                    title: "提示",
                    message: res.data,
                    type: "error",
                })
                // 返回promise的状态是rejected的
                return Promise.reject(res.data)
            }
        },
        // 登录成功后获取用户信息
        async getUserInfo() {
            // 获取用户信息
            const res: any = await userInfo({})
            if (res.code === 200) {
                // 获取中文的用户名
                this.userName = res.data.name
                // 获取用户的头像
                this.avatar = res.data.avatar
                return "ok"
            } else {
                return Promise.reject("fail")
            }
        },

        // 退出登录
        async logout() {
            // 调退出登录的接口
            const res: any = await logout()
            if (res.code === 200) {
                // 数据置空
                this.userName = ""
                this.avatar = ""
                this.token = ""
                localStorage.removeItem("token")
                return "ok"
            } else {
                return Promise.reject(res.message)
            }
        },
    },
})
